package com.ff.javamonkey.ui;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;

import com.ff.javamonkey.R;
import com.ff.javamonkey.util.JavaMonkeyPreferences;

public class PreferencesActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
	// Debugging
	private final String TAG = "PreferencesActivity";
	
	// UI Component
	private SharedPreferences mPrefs;
	private EditTextPreference mIPSetting;
	private EditTextPreference mUserSetting;
	private EditTextPreference mPassSetting;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.addPreferencesFromResource(R.xml.preferences);
		mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
		JavaMonkeyPreferences.setupDefaults(getPreferences(MODE_PRIVATE), getResources());
		
		// Get a reference to the preferences
		mIPSetting = (EditTextPreference)getPreferenceScreen().
			findPreference(JavaMonkeyPreferences.PREFERENCE_IP_SETTING);
		mUserSetting = (EditTextPreference)getPreferenceScreen().
			findPreference(JavaMonkeyPreferences.PREFERENCE_USER_SETTING);
		mPassSetting = (EditTextPreference)getPreferenceScreen().
			findPreference(JavaMonkeyPreferences.PREFERENCE_PASS_SETTING);
		
		setPreferenceSummary();
	}
	
	@Override
    protected void onResume() {
		super.onResume();
		getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }
     	
    @Override
    protected void onPause() {
    	super.onPause();
    	getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }

	public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
		Preference pref = findPreference(arg1);
		if (pref instanceof EditTextPreference) {
			EditTextPreference editText = (EditTextPreference)pref;
			String setValue = editText.getText().toString();
			if (pref.getKey().equalsIgnoreCase(JavaMonkeyPreferences.PREFERENCE_IP_SETTING)) {
				JavaMonkeyPreferences.setIpSetting(setValue);
			}
			else if (pref.getKey().equalsIgnoreCase(JavaMonkeyPreferences.PREFERENCE_USER_SETTING)) {
				JavaMonkeyPreferences.setUserSetting(setValue);
			}
			else if (pref.getKey().equalsIgnoreCase(JavaMonkeyPreferences.PREFERENCE_PASS_SETTING)) {
				JavaMonkeyPreferences.setPassSetting(setValue);
			}
		}
		setPreferenceSummary();
	}
	
	private void setPreferenceSummary() {
		mIPSetting.setSummary(JavaMonkeyPreferences.CURR_PREF_IP_SETTING);
		mUserSetting.setSummary(JavaMonkeyPreferences.CURR_PREF_USER_SETTING);
		mPassSetting.setSummary(JavaMonkeyPreferences.CURR_PREF_PASS_SETTING);
	}
}
